/**
 * 递归组装菜单格式
 */
import { LOGIN_PATH } from '@/enums/commEnum';

export function generatorMenu(routerMap: Array<any>) {
  return filterRouter(routerMap).map((item) => {
    const isRoot = isRootRouter(item);
    const info = isRoot ? item.children[0] : item;
    const currentMenu: { label: string; key: string; icon?: any; children?: any[] } = {
      label: info.meta?.title,
      key: info.name,
      icon: isRoot ? item.meta?.icon : info.meta?.icon,
    };
    // 是否有子菜单，并递归处理
    if (info.children && info.children.length > 0) {
      // Recursion
      currentMenu.children = generatorMenu(info.children);
    }
    return currentMenu;
  });
}

/**
 * 判断根路由 Router
 * */
export function isRootRouter(item) {
  return item.meta?.alwaysShow != true && item.children?.length === 1;
}

/**
 * 排除Router
 * */
export function filterRouter(routerMap: Array<any>) {
  return routerMap.filter((item) => {
    return (
      (item.meta?.hidden || false) != true && !['/:path(.*)*', '/', LOGIN_PATH].includes(item.path)
    );
  });
}

/**
 * 获取一个长度24的随机字符串
 */
export function getRandomStr() {
  return btoa(String(Math.random() * 10));
}

/**
 * 下载
 */
export function download(blob: Blob, filename: string) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

/**
 * 防抖函数
 */
export function debounce(fn: Function, wait: number = 1000) {
  let timer = null;
  return () => {
    if (timer !== null) {
      clearTimeout(timer);
    }
    timer = setTimeout(fn, wait);
  };
}

/**
 * 节流函数
 */
export function throttle(fn: Function, interval: number = 1000) {
  let time = new Date().getTime();
  return () => {
    let now = new Date().getTime();
    if (now - time > interval) {
      time = now;
      setTimeout(fn, interval);
    }
  };
}

/**
 * 重置reactive对象
 */
export function resetReactive(reactive: object) {
  Object.keys(reactive).forEach((k) => {
    delete reactive[k];
  });
}
